package com.ruijie.acl.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.jsf.ListDataModel;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

import com.ruijie.acl.service.TemplateService;
import com.ruijie.acl.task.TaskAclDomain;
import com.ruijie.acl.task.TaskAclUtil;
import com.ruijie.acl.task.model.AccessGroupInfo;
import com.ruijie.acl.task.model.AclDeviceInfo;
import com.ruijie.acl.task.model.TimeRangeInfo;
import com.ruijie.emp.asynchandle.AsyncService;
import com.ruijie.emp.common.BaseAsynLogAction2;
import com.ruijie.foundation.adapter.parser.ParseInfoUtil;
import com.ruijie.foundation.adapter.parser.Parser;
import com.ruijie.foundation.exception.BusinessException;
import com.ruijie.foundation.international.web.function.MessageFunctionLibrary;

@Name("aclTemplateImportAction")
@Scope(ScopeType.PAGE)
public class AclTemplateImportAction extends BaseAsynLogAction2 {

	@SuppressWarnings("unused")
	protected static final Log logger = LogFactory
			.getLog(AclTemplateImportAction.class);

	/**
	 * 上传文件对应的数据


	 */
	private List<UploadItem> files = new ArrayList<UploadItem>();

	private AsyncService templateImportAsyncService;
	
	@In("#{templateService}")
	private TemplateService templateService;
	@In("#{templateAction}") 
	private TemplateAction templateAction;
	
	private InputStream uploadFile;

	private String uploadFileName;
	
	private boolean isFileSizeOver=false;
	
	//导入日志文件
	private List<String> logs=new ArrayList<String>();

	public List<UploadItem> getFiles() {
		return files;
	}

	public void setFiles(List<UploadItem> files) {
		this.files = files;
	}
	
	public ListDataModel getLogDataModel(){
		return logs.size()==0?null:new ListDataModel(logs);
	}
	
	@Override
	public void getLog(){
		
	}

	/**
	 * 上传监听类


	 * 
	 * @param event
	 */
	public void listen(UploadEvent event) {

		if (files == null || files.size() < 1) {
			return;
		}
		UploadItem fileItem = files.get(0);

		uploadFileName = fileItem.getFileName();
		logger.debug("get uploaded file:" + uploadFileName);
		
		/*判断文件是否超过1M*/
		if(fileItem.getFileSize()>1000000){
			isFileSizeOver = true;
			return;
		}

		File file = fileItem.getFile();
		if (file == null) {
			logger.debug("upload is null!!!");
			addGlobalI18nMessage("emp_device_groupimport_importErrorTryAgain");
			return;
		}
		try {
			uploadFile = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			logger
					.error("the file has been uploaded successfully, but it cound't be found in the temp folder of the OS!!!");
			addGlobalI18nMessage("emp_device_groupimport_importErrorTryAgain");
			return;
		}
	}

	@Override
	public Integer getCurrentPercentage() {
		if (currentStatusMessage == null) {
			return 0;
		}
		long total = currentStatusMessage.getTotal();
		long success = currentStatusMessage.getCountOfSuccess();
		long failure = currentStatusMessage.getCountOfFailure();

		if (total > 0) {
			long percentage = (failure + success) * 100 / total;
			return (int) percentage;
		} else {
			return 0;
		}
	}

	@Override
	protected String getLogPage() {
		return "/acl/templateImportLog.seam";
	}

	@Override
	protected AsyncService getServer() {
		return templateImportAsyncService;
	}

	@Override
	public String startService() {
		if(isFileSizeOver){
			throw new BusinessException(MessageFunctionLibrary.i18n_msg("acl_template_upload_size").toString());
		}
		if (uploadFile == null) {
			throw new BusinessException(MessageFunctionLibrary.i18n_msg("emp_device_groupimport_importErrorTryAgain").toString());
		}
		
		AclDeviceInfo deviceInfo= new AclDeviceInfo();
		try {
			 
				
				String textString = readFileString(uploadFile).toString();
				Parser parser = new Parser();
				textString = "\n"+textString+"\n";
				ParseInfoUtil.parseInfo(parser, textString, TaskAclDomain.ACL_PARSER_XML, "acldevicetext", null);
				// ACL 时间段

				List<TimeRangeInfo> timeRangeInfoList = TaskAclUtil.loadTimeRangeInfo(parser);
				deviceInfo.setTimeRangeInfoList(timeRangeInfoList);
				TaskAclUtil.loadTimeInfo(textString, timeRangeInfoList);
				// ACL 组

				ArrayList<AccessGroupInfo> accessGroupList = new ArrayList<AccessGroupInfo>();
				// 标准ACL规则
				accessGroupList.addAll(TaskAclUtil.loadAccessGroupInfo(parser, "standard"));
				// 扩展ACL规则
				accessGroupList.addAll(TaskAclUtil.loadAccessGroupInfo(parser, "extended"));
				// MAC扩展ACL规则
				accessGroupList.addAll(TaskAclUtil.loadAccessGroupInfo(parser, "mac"));
				// 专家扩展ACL规则
				accessGroupList.addAll(TaskAclUtil.loadAccessGroupInfo(parser, "expert"));
				deviceInfo.setAccessGroupInfoList(accessGroupList);
				TaskAclUtil.loadAceInfo(textString, accessGroupList);
				List<String[]> infos=null;
				if(accessGroupList.size()>0){
					deviceInfo.setAccessGroupInfoList(accessGroupList);
					deviceInfo.setTimeRangeInfoList(timeRangeInfoList);
					infos=templateService.loadTemplate(deviceInfo);
				}else{
					throw new BusinessException("acl_templateImport_error");
				}
				//[start]增加导入的提示信息

				if(infos!=null&&infos.size()>0){
					for(String[] msg:infos){
						String code=msg[0];
						if("acl_group_timeRange_import_info".equals(code)){
							//导入时间段：{0}，成功导入时间信息{1}条，失败{2}条。
							String logMsg=this.messageSource.getMessage(code, new Object[]{msg[1],msg[2],msg[3]});
							logs.add(logMsg);
						
						}else if("acl_group_timeRange_import_info_repeat".equals(code)){
							//导入时间段：{0}失败！,时间段名重复。
							String logMsg=this.messageSource.getMessage(code, new Object[]{msg[1]});
							logs.add(logMsg);
						
						}else if("acl_group_timeInfo_import_failed_filter".equals(code)){
							//警告：第{0}条时间信息导入失败！失败原因：{1}
							String logMsg=this.messageSource.getMessage(code, new Object[]{msg[1],this.messageSource.getMessage(msg[2])});
							logs.add("&nbsp;&nbsp;&nbsp;&nbsp;"+logMsg);
						
						}else if("acl_template_ace_import_info".equals(code)){
							//导入模板：{0}，成功导入规则{1}条，失败{2}条。
							String logMsg=this.messageSource.getMessage(code, new String[]{msg[1],msg[2],msg[3]});
							logs.add(logMsg);
							//this.addGlobalI18nMessage(type, msg[1],msg[2],msg[3]);
						}else if("acl_group_ace_import_failed_filter".equals(code)){
							//警告：{0}号规则导入失败！失败原因：{1}
							String reason=this.getI18NMessage(msg[2]);
							String logMsg=this.messageSource.getMessage(code, new String[]{msg[1],reason});
							logs.add("&nbsp;&nbsp;&nbsp;&nbsp;"+logMsg);							
							//this.addGlobalI18nMessage(type, msg[1],reason);							
						}else if("acl_group_ace_import_failed_repeat".equals(code)){
							//警告：{0}号规则导入失败！失败原因：与{1}号规则重复！
							String logMsg=this.messageSource.getMessage(code, new String[]{msg[1],msg[2]});
							logs.add("&nbsp;&nbsp;&nbsp;&nbsp;"+logMsg);
							//this.addGlobalI18nMessage(type, msg[1],msg[2]);
						}else{}
					}
				}
				//[end]
				this.templateAction.setEntityList(null);
		} catch (BusinessException e) {
			throw e;
		} catch (IOException e) {
			throw new BusinessException(e.getMessage());
		} catch(Exception e){
        	throw new BusinessException(e.getMessage());
        }	
		return null;
		//return "/acl/templateIndex.seam";
	}

	@Override
	public void returnTo() {
		redirectTo("/acl/templateIndex.seam");
	}
	
	public void checkExites(String sourceStr,String seachStr,String matchStr){
		String temp = sourceStr.substring(seachStr.length());
		if(temp.indexOf(matchStr)!=-1){
			throw new BusinessException("acl_templateImport_error");
		}
	}

	
	/**
	 * 通过IO流读取到stringBuffer
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public StringBuffer readFileString(InputStream is) throws IOException{
		String line;
		StringBuffer buffer = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		line = br.readLine();
		while(line!=null){
			buffer.append(line);
			buffer.append("\n");
			line = br.readLine();
		}
		return buffer;
	}
	
	

}
